package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.util.DateTimeZoneConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 设备数据Service业务层处理
 * 
 * @author zmc
 * @date 2025-10-19
 */
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper,DeviceData> implements IDeviceDataService
{
    @Autowired
    private DeviceDataMapper deviceDataMapper;

    /**
     * 查询设备数据
     * 
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备数据列表
     * 
     * @param deviceData 设备数据
     * @return 设备数据
     */
    @Override
    public List<DeviceData> selectDeviceDataList(DeviceData deviceData)
    {
        return deviceDataMapper.selectDeviceDataList(deviceData);
    }

    /**
     * 新增设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData)
    {
        return save(deviceData)?1:0;
    }

    /**
     * 修改设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData)
    {
        return updateById(deviceData)?1:0;
    }

    /**
     * 批量删除设备数据
     * 
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids))?1:0;
    }

    /**
     * 删除设备数据信息
     * 
     * @param id 设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id)
    {
        return removeById(id)?1:0;
    }

    @Autowired
    private DeviceMapper deviceMapper;

    @Override
    public void batchInsertFromContentStr(String contentStr) {
        // 判断字符串是否为空
        if(contentStr==null){
            return;
        }

        JSONObject jsonObject = JSONUtil.parseObj(contentStr);

        // 通过设备id获取设备
        String iotId = jsonObject.getByPath("notify_data.header.device_id", String.class);
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getIotId, iotId);
        Device device = deviceMapper.selectOne(queryWrapper);

        if(device==null){
            return;
        }


        JSONObject properties  = (JSONObject)jsonObject.getByPath("notify_data.body.services[0].properties");

        Set<String> keys = properties.keySet();

        String eventTimeStr = jsonObject.get("event_time", String.class);
        LocalDateTime parse = LocalDateTimeUtil.parse(eventTimeStr,"yyyyMMdd'T'HHmmss'Z'");

        LocalDateTime eventTime = DateTimeZoneConverter.utcToShanghai(parse);

        // 准备接受要保存的设备数据
        List<DeviceData> list = new ArrayList<>();
        for (String key : keys) {
            Object value = properties.get(key);

            DeviceData deviceData = BeanUtil.toBean(device, DeviceData.class);
            deviceData.setId(null);
            deviceData.setAccessLocation(device.getBindingLocation());

            deviceData.setFunctionId(key);
            deviceData.setDataValue(value+"");
            deviceData.setAlarmTime(eventTime);

            list.add(deviceData);

        }

        try {
            saveBatch(list);
            redisTemplate.boundHashOps(IOT_DEVICE_LAST_DATA).put(iotId,JSONUtil.toJsonStr(list));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }

    }
    public static final String IOT_DEVICE_LAST_DATA = "iot:device_last_data";
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    @Transactional
    public void cleanOldData(Integer minute) {
     Long  id =  deviceMapper.get(minute);
     deviceMapper.insertA(id);
     deviceMapper.deleteA(id);
    }

 }
